﻿using CKS.Core.Framework;
using Cronos;
using FreeSql;
using Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using ZR.Model.Models._2409;

namespace CKS.PLC.Action.Sys
{
    /// <summary>
    /// 保存设备状态记录，每秒1条记录。
    /// 目的：用于计算OEE
    /// </summary>
    internal class SaveDeviceStatusLogAction : PLCAction
    {
        public SaveDeviceStatusLogAction(DecodeValue _value) : base(_value)
        {
        }

        public override void Execute()
        {
            var _expression = CronExpression.Parse("0/1 * * * * ?", CronFormat.IncludeSeconds);

            var next = _expression.GetNextOccurrence(Value.LastSaveTime, TimeZoneInfo.Local);
            var delay =next.Value - DateTimeOffset.Now;
            if(delay.TotalMilliseconds < 990 && delay.TotalMilliseconds>0 )
            {
                return; //两次间隔不到1秒
            }
            Value.LastSaveTime = DateTimeOffset.Now;
           // EventBus.AddLog($"OEE测试信息 {DateTime.Now.ToString("HH:mm:ss")}");

            //读取状态信息存储到数据库
            var RunState = Value.GetLinkData(1).ToInt();
            var DeviceMode = Value.GetLinkData(1).ToInt();

            /*
                运行状态：1=空闲，2=运行中，3=故障；4=待料中；
                设备模式：1=空模式；2=手动；4=初始化；8=自动；16=自动模式下暂停;
             */
            var log = new DeviceStatusLog()
            {
                DeviceCode = Value.SiemensClient.PlcInfo.WorkstationCode,
                PlcId = Value.SiemensClient.PlcInfo.Id,
                RunState = RunState,
                DeviceMode = DeviceMode,
                IsRunning = RunState == 2 ? 1:0
            };
            conn.Insert(log).ExecuteAffrows();
        }
    }
}
